package org.ithasu.tools.net.twitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.ithasu.tools.ConfigTools;
import org.ithasu.tools.Console;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TwitterTools {

	private final static String CONFIG_CONSUMER_KEY = "twitter.consumerKey";
	private final static String CONFIG_CONSUMER_SECRET = "twitter.consumerSecret";
	private final static String CONFIG_USER_KEY = "twitter.userKey";
	private final static String CONFIG_USER_SECRET = "twitter.userSecret";

	protected TwitterTools() {
	}

	// -- Auth ----------------------------------------

	public static boolean auth() {
		try {
			TwitterFactory tf = new TwitterFactory();
			Twitter twitter = tf.getInstance();
			String consumerKey = ConfigTools.getProperty(CONFIG_CONSUMER_KEY);
			String consumerSecret = ConfigTools.getProperty(CONFIG_CONSUMER_SECRET);
			if (consumerKey == null || consumerSecret == null) {
				Console.error("Error: missing consumer key/secret for twitter");
				return false;
			}
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			RequestToken requestToken = twitter.getOAuthRequestToken();
			AccessToken accessToken = null;
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			while (null == accessToken) {
				System.out.println("Open the following URL and grant access to your account:");
				System.out.println(requestToken.getAuthorizationURL());
				System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:");
				String pin = br.readLine();
				if (pin.length() > 0) {
					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
				} else {
					accessToken = twitter.getOAuthAccessToken();
				}
			}
			// persist to the accessToken for future reference.
			ConfigTools.setProperty(CONFIG_USER_KEY, accessToken.getToken());
			ConfigTools.setProperty(CONFIG_USER_SECRET, accessToken.getTokenSecret());
			return true;
		} catch (TwitterException te) {
			if (401 == te.getStatusCode()) {
				Console.error("Unable to get the access token.");
			} else {
				Console.error(te);
			}
			return false;
		} catch (Exception e) {
			Console.error(e);
			return false;
		}
	}


	public static void main(String[] args) {
		String appName = "ithasu-tools";
		if (args.length < 1) {
			Console.error("Usage: <config app name>");
		} else {
			appName = args[0];
		}
		ConfigTools.load(appName);
		auth();
		ConfigTools.save(appName);
	}
}
